// src/utils/request.js
import { extend } from 'umi-request';
import { getSessionStorageInfo, getLocalStorageInfo } from './localStorageInfo';
import { notification } from 'antd';
// 接口环境地址
let gatewayUrl = process.env.baseUrl;

const bsinRequest = extend({
  // 配置选项
  errorHandler: (error) => {
    // 错误处理
    const { response } = error;
    if (response && response.status) {
      // 根据不同的响应状态码处理错误
      const errorText = `请求错误 ${response.status}: ${response.statusText}`;
      console.error(errorText);
    } else if (!response) {
      console.error('网络异常，无法连接服务器');
    }
    return response;
  },
});


// 请求拦截
bsinRequest.interceptors.request.use((url, config) => {
  // 请求方法统一为 POST
  config.method = 'POST';
  console.log(gatewayUrl)
  // 获取userInfo和token
  // let userInfo = getLocalStorageInfo('userInfo');
  let token = getSessionStorageInfo('token')?.token;

  // let token =
  //   'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiIxNTM1OTg0MzA0NTI4NjkxMjAwIiwidXNlcm5hbWUiOiJhZG1pbiIsInRlbmFudElkIjoiNjM0NTgyNDQxMzc2NDE1NzQ0MCIsImJpelJvbGVUeXBlIjoiOTkiLCJiaXpSb2xlVHlwZU5vIjoiMTUzNTk4NDMwNDUyODY5MTIwMCIsImlhdCI6MTczNzQzMTUzNywiZXhwIjozNDc0ODY2Njc0fQ.41UJ34bvqnOmWvNOAoBPNXhIqKx4y95f0O-ajBHChsY';
  // 判断token和用户信息是否存在
  // if (
  //   (!token || !userInfo) &&
  //   config.methodName !== 'getIssueApps' &&
  //   config.methodName !== 'login'
  // ) {
  //   history.push('/login');
  // }
  console.log(gatewayUrl)
  // 判断一些
  const headers = {
    'Content-Type': 'application/json',
    Accept: 'application/json',
    Authorization: token || "",
  };

  let pagination;
  if (config?.bizParams?.pageSize) {
    pagination = {
      pageSize: config?.bizParams?.pageSize,
      pageNum: config?.bizParams?.current,
    };
    delete config?.bizParams?.pageSize;
    delete config?.bizParams?.current;
  }
  // 组装报文
  let data = {}
  if (config?.version) {
    headers.version = config?.version;
  }

  if (pagination) {
    data = {
      ...config.bizParams,
      pagination,
    };
  } else {
    data = {
      ...config.bizParams
    };
  }
  config.headers = {
    ...headers,
  };

  console.log("config")
  console.log(config)
  const requestUrl = gatewayUrl + config.url;

  return {
    url: requestUrl,
    options: { data, ...config },
  };
});

// response拦截器, 处理response
bsinRequest.interceptors.response.use(
  (response, options) => {
    if (response.status === 200) {
      return response
        .clone()
        .json()
        .then((body) => {
          console.log(body)
          
          // 检查业务错误码
          if (body?.code !== 0) {
            let errorMessage = body?.message || '请求失败';
            
            // 针对特定业务错误码显示友好提示
            if (body?.code === 500) {
              errorMessage = '服务端异常，程序员小哥哥正在全力抢修～';
            } else if (body?.code === 401) {
              errorMessage = '登录已过期，请重新登录';
            } else if (body?.code === 403) {
              errorMessage = '权限不足，请联系管理员';
            } else if (body?.code === 404) {
              errorMessage = '请求的资源不存在';
            }
            
            notification.error({
              message: '操作失败',
              description: errorMessage,
              duration: 4.5,
            });
            
            // 修改响应数据，防止 errorThrower 再次处理导致重复提示
            body = {
              ...body,
              success: true, // 标记为成功，避免 errorThrower 抛出错误
              _errorHandled: true // 添加标记表示已处理错误
            };
          }
          
          return body;
        });
    } else {
      // HTTP状态码错误处理
      let errorMessage = '网络请求失败';
      if (response.status === 401) {
        errorMessage = '登录已过期，请重新登录';
      } else if (response.status === 403) {
        errorMessage = '权限不足，请联系管理员';
      } else if (response.status === 404) {
        errorMessage = '请求的资源不存在';
      } else if (response.status >= 500) {
        errorMessage = '服务端异常，请稍后重试';
      }
      
      notification.error({
        message: '请求失败',
        description: errorMessage,
        duration: 4.5,
      });
      
      return false;
    }
  },
  {
    global: false,
  },
);

export default bsinRequest;
